//
//  FileWebViewController.m
//  FengyuanXS
//
//  Created by 王冬 on 2020/8/24.
//  Copyright © 2020 王冬. All rights reserved.
//

#import "FileWebViewController.h"
#import "ZBWKWebView.h"
#import "AFNetworking/AFNetworking.h"
@interface FileWebViewController ()<WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong) UIProgressView    *progressView;

@property (nonatomic, copy) NSString *headerString;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, copy) NSString *footUrl;
@property (nonatomic, copy) NSString *fileUrl;
@end

@implementation FileWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.titleStr;
   self.webView = [[WKWebView alloc] init];
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";

             WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
             WKUserContentController *wkUController = [[WKUserContentController alloc] init];
             [wkUController addUserScript:wkUScript];

             WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
             wkWebConfig.userContentController = wkUController;
 
             [wkWebConfig.userContentController addScriptMessageHandler:self name:@"downfile"];
    
    
             // 创建设置对象
             WKPreferences *preference = [[WKPreferences alloc]init];
             // 设置字体大小(最小的字体大小)
             preference.minimumFontSize = 12;
             // 设置偏好设置对象
          //   wkWebConfig.preferences = preference;
             self.webView= [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];
     
//      WKDelegateController *delegateController = [[WKDelegateController alloc]init];
//      delegateController.delegate = self;
      
    
    
      [self.view addSubview:self.webView];

      UIEdgeInsets padding = UIEdgeInsetsMake(0, 0, 0, 0);
      [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
          make.edges.equalTo(self.view).with.insets(padding);
      }];
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0.8)];
      self.progressView.progressTintColor = [UIColor blueColor];
    
      //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
      self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
      [self.webView addSubview:self.progressView];
      [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
       self.webView.UIDelegate = self;
       self.webView.navigationDelegate = self;
       self.webView.allowsBackForwardNavigationGestures = NO;
       self.webView.allowsLinkPreview = YES;


    [self getdata];
        
}
-(void)downBtn{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.fileUrl]];
    
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //打印下载进度
        NSLog(@"%f",1.0 * downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);

        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *fullPath = [filePath stringByAppendingPathComponent:response.suggestedFilename];
        
        NSLog(@"%@",fullPath);
        
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSLog(@"%@",filePath);
        NSLog(@"completionHandler----%@",error);
        if (error) {
            [[ToastManager shardInstance]showToast:@"下载失败"];
            
        }
        else{
           NSArray *items = @[@"",@"",filePath];
//            UIActivityViewController *activityController = [[UIActivityViewController alloc]initWithActivityItems:activityItemsArray applicationActivities:nil];
//            activityController.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
//                if (completed) {
//                    [[ToastManager shardInstance] showToast:@"保存成功"];
//                }
//            };
//            [self.navigationController presentViewController:activityController animated:YES completion:nil];
            
            
            UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
              if (@available(iOS 11.0, *)) {//UIActivityTypeMarkupAsPDF是在iOS 11.0 之后才有的
                  activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypeOpenInIBooks,UIActivityTypeMarkupAsPDF];
              } else if (@available(iOS 9.0, *)) {//UIActivityTypeOpenInIBooks是在iOS 9.0 之后才有的
                  activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypeOpenInIBooks];
              }else {
                  activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail];
              }
              activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                  if (completed) {
                     
                     
                  }else {
                    
                  }
              };
//这儿一定要做iPhone与iPad的判断，因为这儿只有iPhone可以present，iPad需pop，所以这儿actVC.popoverPresentationController.sourceView = self.view;在iPad下必须有，不然iPad会crash，self.view你可以换成任何view，你可以理解为弹出的窗需要找个依托。
//              UIViewController *vc = target;
//              if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
//                  activityVC.popoverPresentationController.sourceView = vc.view;
//                  [vc presentViewController:activityVC animated:YES completion:nil];
//              } else {
//                  [vc presentViewController:activityVC animated:YES completion:nil];
//              }
            
        }
        
    }];
    
    [downTask resume];
}




   
  





-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    {
      self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
                                               initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                                               style:UIBarButtonItemStyleDone
                                               target:self
                                               action:@selector(leftBarButtonClick)];
          
      }
}
- (void)leftBarButtonClick {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getdata{
    [[ToastManager shardInstance]showSystemProgress:self.view];
    
    [[ApiManager ShardInstance]getDetailNoticeID:self.noticeID resultBlock:^(NSDictionary *data, NSError *error) {
        BaseModel *model = [BaseModel mj_objectWithKeyValues:data];
        if (model.code == 1) {
             [[ToastManager shardInstance]hideProgress:self.view];
            

            
//            党政之声
            
            if ([self.titleStr isEqualToString:@"党政之声"]) {
              self.headerString = @"<html><head><meta charset='utf-8'><title></title><style type='text/css'> .tittle{font-size: 25px;font-weight: bold;text-align: center;margin-top: 10px;}.tips{padding: 0 5px 0 5px;color: #b3aeae;font-size: 15px;display: flex;justify-content: space-between; align-items: center;margin-bottom: 20px;}.time{margin-right:10px;}.handle{ padding-left: 30px;margin-top:-60px;font-size: 20px;text-decoration: none; }.handle:visited {color: blue;text-decoration:none;}</style> </head> <body style='position:relative;box-sizing:border-box'><div style='position:absolute;left:50%;transform:translateX(-10%);top:0;'><div class='tittle'>";
            }else{
                self.headerString = @"<html><head><script language='javascript'>function downfile() {window.webkit.messageHandlers.downfile.postMessage({body: 'hello world!'});}</script><meta charset='utf-8'><title></title><style type='text/css'> .tittle{font-size: 25px;font-weight: bold;text-align: center;margin-top: 10px;}.tips{padding: 0 5px 0 5px;color: #b3aeae;font-size: 15px;display: flex;justify-content: space-between; align-items: center;margin-bottom: 20px;}.time{margin-right:10px;}.handle{ padding-left: 10px;margin-top:-60px;font-size: 17px;text-decoration: none; }.handle:visited {color: blue;text-decoration:none;}</style> </head> <body style='position:relative;box-sizing:border-box;width:100vw!important'><div style='position:absolute;left:50%;transform:translateX(-50%);top:0;width:100%!important'><div class='tittle'>";

            }
            
            
           
             
            NSString *title = [NSString stringWithFormat:@"%@",data[@"rs"][@"title"]];
            
            NSString *name = [NSString stringWithFormat:@"%@%@",@"</div><div class='tips'><div>",data[@"rs"][@"user_shortname"]];
            
            NSString *ttt = [NSString stringWithFormat:@"%@",data[@"rs"][@"create_time"]];
            NSString *time = [NSString stringWithFormat:@"%@%@%@",@"</div><div> <span class='time'>",[self ConvertStrToTime:ttt],@"</div></div>"];
            
            
            
            NSString *moreStr = [NSString stringWithFormat:@"%@",data[@"rs"][@"more"]];
            if ([moreStr isEqualToString:@"<null>"]) {
                self.footUrl = [NSString stringWithFormat:@"%@%@%@",@"<div class='test'><div class='handle' href="">",@" ",@"</div></div>"];
               
            }else{
                
                self.fileUrl = [NSString stringWithFormat:@"%@%@",BaseImgUrl,data[@"rs"][@"more"][@"files"][0][@"url"]];
               // self.footUrl = [NSString stringWithFormat:@"%@%@%@%@%@",@"<div class='test'><a class='handle' href=",self.fileUrl,@">",data[@"rs"][@"more"][@"files"][0][@"name"],@"</div></div>"];
                
                 // self.footUrl = [NSString stringWithFormat:@"%@%@%@",@"<div><a href='#' class='handle' onclick='downfile()'>W3School @"</a></div>"];
                 self.footUrl = [NSString stringWithFormat:@"%@%@%@",@"<div><a class='handle' href='#' class='handle' onclick='downfile()'>",data[@"rs"][@"more"][@"files"][0][@"name"],@"</div></div>"];
            }
            
            
         
       
                        
        // self.fileUrl = [NSString stringWithFormat:@"%@%@",BaseImgUrl,data[@"rs"][@"more"][@"files"][0][@"url"]];
            

            NSString * aaa = @"</body></html>";

             NSString *html = [NSString stringWithFormat:@"%@",data[@"rs"][@"content"]];
            
            //@"tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1"
            
            NSString *strUrl = [html stringByReplacingOccurrencesOfString: @"tp=webp&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1" withString:@""];
       
            
             [self.webView loadHTMLString:[NSString stringWithFormat:@"%@%@%@%@%@%@%@",self.headerString,title,name,time,strUrl,self.footUrl,aaa] baseURL:nil];
            
            
        }
        
    }];
    
    
}

//时间戳变为格式时间
- (NSString *)ConvertStrToTime:(NSString *)timeStr

{
    
    long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    //    long long time=[timeStr longLongValue] / 1000;
    
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*timeString=[formatter stringFromDate:date];
    
    return timeString;
    
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    // [self endRefresh];
    
    if ([self.progressView isDescendantOfView:self.webView]) {
        self.progressView.hidden = NO;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    }
}

//页面完成加载时调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
      
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([self.progressView isDescendantOfView:self.webView]) {
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            self.progressView.progress = self.webView.estimatedProgress;
            if (self.progressView.progress == 1) {
                /*
                 *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
                 *动画时长0.25s，延时0.3s后开始动画
                 *动画结束后将progressView隐藏
                 */
                
                WS(weakSelf);
                [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                    weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
                } completion:^(BOOL finished) {
                    weakSelf.progressView.hidden = YES;
                    
                }];
            }
        }else{
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    //message.body传值的内容。
    //前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
    //    window.webkit.messageHandlers.refreshApp.postMessage({body: 'hello world!'});
    if ([message.name isEqualToString:@"downfile"]) {
        NSLog(@"%@",message.body);
        [self downBtn];
    }
}

@end
